package streams;

import java.util.ArrayList;
import java.net.*;
import java.io.*;
import javax.xml.parsers.*; 
import org.w3c.dom.*; 
import streams.channel;

public class channelList {

	protected String listUrl;
	protected ArrayList <channel> Channels;
	
	// Default Constructor
	public channelList ()
	{
		listUrl = "";
		Channels = new ArrayList <channel> ();
	}
	
	
	// Load a Channel List from specified URL
	public void LoadChannelList( String url ) throws Exception
	{
		this.listUrl = url;
		
		try
		{
			// Load Channel List to a InputStream
			InputStream channelListStream = LoadChanneListStream(url);
	        
	        // Parse the InputStream
			Document xmlChannelList = parseXmlStream(channelListStream);         
	        
			// Load Channel List to "Channels" objects
			
			// TODO !!!
	        
		}
		catch(Exception e)
		{
			throw e;
		}
	}
	
	
	// Load Channel List from URL to a Stream
	protected InputStream LoadChanneListStream ( String url ) throws Exception
	{
		// Read the URL stream
		URL fileUrl = new URL(url);
		BufferedReader inBufferReader = new BufferedReader(new InputStreamReader(fileUrl.openStream()));

		// BufferedReader to StringBuffer
		StringBuffer inputStrBuffer = new StringBuffer();
		String inputLine;
	    while ((inputLine = inBufferReader.readLine()) != null)
        {
	    	inputStrBuffer.append(inputLine).append("\n");
        }
	    inBufferReader.close();
	    
	    // StringBuffer to String
	    String inputString = inputStrBuffer.toString();  
		
	    // String to InputStream
		InputStream inputStream = new ByteArrayInputStream(inputString.getBytes());  
		
		return inputStream;
	}
	
	
	// Parse XML Stream
	protected Document parseXmlStream ( InputStream inputStream ) throws Exception
	{
		DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();  
	       
        xmlFactory.setValidating(false);  
        xmlFactory.setIgnoringComments(false);  
        xmlFactory.setIgnoringElementContentWhitespace(true);  
        xmlFactory.setNamespaceAware(true);  
        
        DocumentBuilder xmlbuilder = xmlFactory.newDocumentBuilder(); 
        
        Document xmlDoc = xmlbuilder.parse(inputStream);  
        
        return xmlDoc;
	}
}
